package lazy.text;

public class StringRetrieve {
	private String text;
	private String retrieveStartString;
	private String retrieveEndString;
	private int startIndex;
	
	public StringRetrieve(String text, String retrieveStartString, String retrieveEndString) {
		if(text==null
		|| retrieveStartString==null
		|| retrieveEndString==null)
			throw new IllegalArgumentException("text、retrieveStartString或retrieveEndString為null。");
		
		this.text = text;
		this.retrieveStartString = retrieveStartString;
		this.retrieveEndString = retrieveEndString;
		this.startIndex = 0;
	}
	public void changeText(String text) {
		this.text = text;
		this.startIndex = 0;
	}
	public void changeRetrieveStartString(String retrieveStartString) {
		this.retrieveStartString = retrieveStartString;
		this.startIndex = 0;
	}
	public void changeRetrieveEndString(String retrieveEndString) {
		this.retrieveEndString = retrieveEndString;
		this.startIndex = 0;
	}
	public String retrieveFirst() {return retrieve(0);}
	public String retrieveNext() {return retrieve(startIndex);}
	public String retrieveLast() {return retrieve(text.lastIndexOf(retrieveStartString));}
	private String retrieve(int fromIndex) {
		String s = null;
		int beginIndex = text.indexOf(retrieveStartString, fromIndex);
		if(beginIndex!=-1) {
			startIndex = beginIndex+retrieveStartString.length();
			int endIndex = text.indexOf(retrieveEndString, startIndex);
			if(endIndex!=-1) {
				s = text.substring(startIndex, endIndex);
			}
		}
		return s;
	}
}
